var ctr_mentionPOST = 0;
var pathname = window.location.pathname;
(function($) {

    $.fn.mention_post = function(options) {
        var dis = this;
        if(options=="destroy"){
            $(dis).off(".mentionPost");
            $(dis).trigger('autosize.destroy');
        }else{
            if(ctr_mentionPOST==0){
                $("body").append('<div class="mentionSearchChoice" style="position:absolute;background-color:white"></div>');
            }
            ctr_mentionPOST++;
            
            var settings = $.extend({
                json : "",
                prefix : "",
                highlightClass : "highlightBackground",
                countDisplayChoice : 5
                }, options);
            
            searchElement_post(dis,settings);

            //append styles and html elements for list

            addHtmlChars_post(dis);
        }
    }

}(jQuery));
var countIndexSearch = 0; // count of total search(this is for keydown and keyup)
function searchElement_post(dis,settings){
    var data = settings.json;
    
    var value_toSearch = ""; // value on the textbox or textarea
    var ret = ""; // return search suggestion
    
    var totalIndexSearch = 0; // total search
    var aa = "";
    var reg = "";
    var reg_hidden = "";
    $(dis).on({
        "keydown.mentionPost" :function(event){
            totalIndexSearch = $(".mentionSearchChoice").find(".mentionList").length;
            dis = this;
            if(event.which==40){
                if(countIndexSearch<totalIndexSearch){
                    countIndexSearch++;
                    event.preventDefault();
                }else{
                    countIndexSearch = 0;
                }
                
            }else if(event.which==38){
                if(countIndexSearch>0){
                    countIndexSearch--;
                    event.preventDefault();
                }else{
                    countIndexSearch = totalIndexSearch;
                }
                
            }else if(event.which==13){
                if(totalIndexSearch>0){
                    addMention(this,settings)
                    $(".mentionSearchChoice").html("")
                    countIndexSearch = 0;
                    event.preventDefault();
                }
                
            }else if(event.which==8){
                if($(dis).val()==""){
                    //$(dis).prev().remove()
                    
                    event.preventDefault();
                }
            }
            // console.log(countIndexSearch+" "+totalIndexSearch)
            $(".mentionSearchChoice").children(".mentionList").removeClass("mentionActive")
            $(".mentionSearchChoice").children(".mentionList").eq(countIndexSearch).addClass("mentionActive")
            

            /*PALITAN ANG LAMAN NG HIDDEN AT UNG NASA LIKOD NA MAY BACKGROUND PWERA DUN SA NAKA @[STRING]*/
            var pattern = /@\[(.*?)\]/g;
            value_txt = $(this).val();
            var forHidden = $(this).val();
            value_txt = value_txt.replace(/\n/g, '<br>');
            value_txt = htmlEntities(value_txt)
            value_txt = nl3br(value_txt);
            var array_push = [];
            $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").find("span").each(function(){
                if(array_push.indexOf($(this).text())==-1){
                    reg = new RegExp($(this).text(),"g");
                    reg_hidden = new RegExp($(this).text(),"g")
                    value_txt = value_txt.replace(reg,"<span style=''  data_id='"+ $(this).attr("data_id")  +"' first_name='"+ $(this).attr("first_name")  +"' last_name='"+ $(this).attr("last_name")  +"'><b class='"+ settings.highlightClass +"'>"+$(this).text()+"</b></span>");
                    forHidden = forHidden.replace(reg,"@["+$(this).attr("last_name")+"_"+$(this).attr("first_name")+":"+ $(this).attr("data_id") +"]");
                }
                array_push.push($(this).text())
            })
            $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").html(value_txt)
            
            $(dis).closest(".mentionContainer").find(".mentionHiddenText").val(forHidden);
        },  
        "keyup.mentionPost" : function(event){
                ret = ""
                var ctrToAppend = 0;
                var value_txt = $(this).val();
                var forHidden = $(this).val();
                dis = this;
                if(event.which!=40 && event.which!=38){
                    value = value_txt.split(/\s@|<br \/>@/g);
                    var j = value.length-1;
                    var value_converted = value[j];

                    if(j==0 && value_txt.charAt(0)=="@"){
                        // check if the first element of array has "@" on the first character!
                        value_converted = "@"+value[j].substr(1,value[j].length);
                    }
                    if(j>0){
                        value_converted = "@"+value[j];
                    }
                    value_converted = "@"+AlertPrevWord(this)

                    // console.log(value[j])
                    // console.log(value_converted)
                    //for(var j in value){
                        
                        
                        // value_toSearch = $.trim(value_converted.toLowerCase());
                        if(value[j]){
                            if(value_converted && value_converted.charAt(0)=="@"){
                                for(var i in data){
                                    if(data[i]['ws']){
                                        value_toSearch = $.trim(value_converted.toLowerCase());
                                        if(data[i]['name'].toLowerCase().indexOf(value_toSearch) !== -1 && value_toSearch!=data[i]['name'].toLowerCase()){
                                            ret += '<div class="mentionList" style="" data_id="'+ data[i]['id'] +'" first_name="'+ data[i]['first_name'] +'" last_name="'+ data[i]['last_name'] +'">'+ if_null(data[i]['user_image']) +'<span class="mentionList_txt">'+ data[i]['name'] +'</span></div>';
                                            ctrToAppend++;
                                            if(ctrToAppend==settings.countDisplayChoice){
                                                break;
                                            }
                                        }
                                    }else{
                                        value_toSearch = $.trim(value_converted.substr(1,value_converted.length).toLowerCase());
                                        if(data[i]['name'].toLowerCase().search(value_toSearch) !== -1){
                                            ret += '<div class="mentionList" style="" data_id="'+ data[i]['id'] +'" first_name="'+ data[i]['first_name'] +'" last_name="'+ data[i]['last_name'] +'">'+ if_null(data[i]['user_image']) +'<span class="mentionList_txt">'+ data[i]['name'] +'</span></div>';
                                            ctrToAppend++;
                                            if(ctrToAppend==settings.countDisplayChoice){
                                                break;
                                            }
                                        }    
                                    }
                                    // if(data[i]['name'].toLowerCase().search(value_toSearch) !== -1){
                                    //     if(data[i]['ws']){
                                    //         ret += '<div class="mentionList" style="" data_id="'+ data[i]['id'] +'" first_name="'+ data[i]['first_name'] +'" last_name="'+ data[i]['last_name'] +'">'+ if_null(data[i]['user_image']) +'<span class="mentionList_txt">'+ data[i]['name'] +'</span></div>';
                                    //     }else{
                                    //         ret += '<div class="mentionList" style="" data_id="'+ data[i]['id'] +'" first_name="'+ data[i]['first_name'] +'" last_name="'+ data[i]['last_name'] +'">'+ if_null(data[i]['user_image']) +'<span class="mentionList_txt">'+ data[i]['name'] +'</span></div>';
                                    //     }
                                        
                                    // }
                                }
                                var margin_searchChoice = $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").height()+9;
                                var width = $(this).outerWidth();
                                var top = ($(this).offset().top-$(document).scrollTop())+$(this).outerHeight();
                                var left = $(this).offset().left;

                                $(".mentionSearchChoice").css({
                                    width:width,
                                    top:top,
                                    left:left
                                }).html(ret);
                                var windowBottom = $(window).outerHeight()+$(document).scrollTop();
                                var searchChoiceBottom = $(".mentionSearchChoice").outerHeight()+$(".mentionSearchChoice").offset().top;
                                // console.log(windowBottom+"\n"+searchChoiceBottom);
                                if(searchChoiceBottom>windowBottom){
                                    $(".mentionSearchChoice").css({
                                        top: top-($(".mentionSearchChoice").outerHeight()+$(this).outerHeight())
                                    })
                                }
                                $(".mentionSearchChoice").children(".mentionList").eq(0).addClass("mentionActive")
            
                            }else{
                                //console.log("hindi @ ung simula")
                                $(".mentionSearchChoice").html("")
                                countIndexSearch = 0;
                            }
                        }else{
                            //console.log("Di Pwede walang laman")
                            $(".mentionSearchChoice").html("")
                            countIndexSearch = 0;
                        }
                    //}

                    // $(dis).closest(".mentionContainer").find(".mentionHiddenText").val();
                    //$(dis).closest(".mentionContainer").find(".mentionHiddenText").val(value_txt);
                    
                    /*PALITAN ANG LAMAN NG HIDDEN AT UNG NASA LIKOD NA MAY BACKGROUND PWERA DUN SA NAKA @[STRING]*/
                    var pattern = /@\[(.*?)\]/g;
                    value_txt = value_txt.replace(/\n/g, '<br>');
                    value_txt = htmlEntities(value_txt)
                    value_txt = nl3br(value_txt)
                    var array_push = [];
                    $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").find("span").each(function(){
                        // console.log($(this))
                        if(array_push.indexOf($(this).text())==-1){
                            reg = new RegExp($(this).text(),"g");
                            reg_hidden = new RegExp($(this).text(),"g")
                            value_txt = value_txt.replace(reg,"<span style='' data_id='"+ $(this).attr("data_id") +"' first_name='"+ $(this).attr("first_name") +"' last_name='"+ $(this).attr("last_name") +"'><b class='"+ settings.highlightClass +"'>"+$(this).text()+"</b></span>");
                            forHidden = forHidden.replace(reg,"@["+$(this).attr("last_name")+"_"+$(this).attr("first_name")+":"+ $(this).attr("data_id") +"]");
                        }
                        array_push.push($(this).text())
                    })
                    $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").html(value_txt)
                    
                    $(dis).closest(".mentionContainer").find(".mentionHiddenText").val(forHidden);
                }
                var self = this;
                if($(dis).prop("tagName")=="TEXTAREA"){
                    $(this).autosize({append: "\n"});
                }
                
                $("#textarea-popup-comment").perfectScrollbar("update");
                $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").css("height",$(this).height());
                $(".mentionList").click(function(){
                    // alert("do the same function in enter")
                    $(dis).focus();
                    addMention(self,settings)

                    $(".mentionSearchChoice").html("")

                    countIndexSearch = 0;

                    $(dis).trigger("keyup");
                })
        }
    })
    $(dis).addClass("mentionPostDis");          
    $("body").mousedown(function(evs){
        target = (window.event) ? window.event.srcElement /* for IE */ : evs.target;
        if ($(target).closest(".mentionSearchChoice").length >= 1 || $(target).closest(".mentionPostDis").length >=1) { //has a parent named class
            //walang gagawin
        } else {
            $(".mentionSearchChoice").html("")
        }
    })
    $("body").on("mouseenter",".mentionList",function(){
        $(".mentionList").removeClass("mentionActive");
        $(this).addClass("mentionActive");
        countIndexSearch = $(this).index();
    })
    
    $("body").on("click",".mentionSelectedContainer",function(){
        //$(dis).focus();
    })
}
function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function getJSONFromFile (path,callback){
    $.getJSON(path,function(data){
        callback(data)
    });
}
function addHtmlChars_post(dis){
    var width = $(dis).width()+"px;";
    var padding = $(dis).css("padding");
    var font_size = $(dis).css("font-size");
    var width_cont = $(dis).width()+10+"px";
    var line_height = "20px";
    var margin_top = "";
    var margin_left = "5px";
    var strFN = "before";
    var font_style = "'pt sans', arial, helvetica, sans-serif";
    var containerMarginTop = "10px;";
    if($(dis).hasClass("reply")){

        /*OLD UI*/
        // $(dis).css({
        //     "background-color": "transparent",
        //     "white-space":"pre-wrap",
        //     //"width":"585px",
        //     "padding":"5px 10px 5px 5px"
        // })  
        // padding = "5px 10px 5px 5px";
        // width_cont = "";
        // //width_cont = "590";
        // width = "585px;";
        // //width = "";
        // line_height = "15px";
        // margin_top = "5px";
        // margin_left = "0px";
        /*NEW UI*/
        $(dis).css({
            "background-color": "transparent",
            "white-space":"pre-wrap",
            //"width":"585px",
            "padding":"5px 10px 5px 5px"
        })  
        padding = "5px 10px 5px 5px";
        width_cont = "";
        //width_cont = "590";
        width = "620px;";
        //width = "";
        line_height = "18px";
        margin_top = "7px";
        margin_left = "0px";
        font_style = 'open_sansregular';
    }else if($(dis).hasClass("comment-popup")){
        width_cont = "100%"
        margin_left = "0px";
        width = "95%;border-radius:0px;position:relative;border:1px solid #D5D5D5;";
        line_height = "15px";
        $(dis).css({
            "background-color": "transparent",
            "position":"absolute",
            "z-index":"1",
            "box-shadow":"none",
            "-webkit-box-shadow":"none",
            "border":"none",
            "outline":"none",
            "width":"95%",
            // "padding":"5px 10px 5px 5px"
        })
        strFN = "after";
        
        if($(dis).closest("body").find(".fl-main-container").length>0){
            width = "95%;border-radius:0px;position:relative;border:1px solid #D5D5D5;";
            font_style = "open_sansregular";
            line_height = "18px";

        }
        containerMarginTop = "";
    }else if($(dis).hasClass("getPost")){
        font_size = "14px";
        width_cont = "";
        //width_cont = "700";
        if($(dis).closest(".fl-main-content-wrapper").length>0){
            margin_left = "9px";
            //margin_top = "8px";

        }
        width = "685px;";
        if(pathname=="/user_view/announcements"){
            width = "1084px !important;"
            font_style = "open_sansregular !important";
            margin_left = "2px";
        }
    }else if($(dis).hasClass("obj_prop")){ // for testing
        $(dis).css({
            "background-color": "transparent",
            "position":"absolute",
            "z-index":"1",
            "box-shadow":"none",
            "-webkit-box-shadow":"none",
            //"border":"none",
            "resize":"none",
        })
        strFN = "after";
        line_height = "14px";
        margin_left = "0px"
        width = (width+2)+";border: 1px solid #D5D5D5;;display:none;"
        margin_top = "4px";
    }else if($(dis).hasClass("wfSettings")){
        strFN = "after";
        width = $(dis).width()+"px;display:none;";
        width_cont = "auto";
    }else if($(dis).hasClass("workflow-reference-fields-formula")){
        $(dis).css({
            "z-index":"1",
            "box-shadow":"none",
            "-webkit-box-shadow":"none",
            "border":"none",
            "resize":"none",
        })
        strFN = "after";
        width = $(dis).width()+"px;display:none;";
        width_cont = "100%";
    }else if($(dis).hasClass("report-field-formula")){
        $(dis).css({
            "z-index":"1",
            "box-shadow":"none",
            "-webkit-box-shadow":"none",
            "border":"none",
            "resize":"none",
        })
        strFN = "after";
        width = $(dis).width()+"px;display:none;";
        width_cont = "100%";
    }else if($(dis).hasClass("mid_rule_formula")){
        strFN = "after";
        width = $(dis).width()+"px;display:none;";
    }

    //fixed search choices
    if($(dis).closest("#popup_container").length>=1){
        $(".mentionSearchChoice").css({
            "position":"fixed"
        })
    }
    
    if($(this).closest(".mentionContainer").length===0){
        $(dis).wrap('<div class="mentionContainer" style="width: '+width_cont+';margin-top:'+ containerMarginTop +'"></div>');
        $(dis)[strFN]('<div class="mentionSelectedContainer" style="width:'+width+'padding:'+ padding +';font-size:'+ font_size +';line-height:'+ line_height +';margin-top:'+ margin_top +';margin-left:'+ margin_left +';font-family:'+ font_style +'"></div>');
        $(dis).after('<input type="hidden" class="mentionHiddenText">');
    }
}

function addMention(dis,settings){
    var prefix = settings.prefix;
    var activeEle = $(".mentionSearchChoice").find(".mentionActive");
    var value_txt = $(dis).val();
    var value_arr = value_txt.split(/\s@|<br \/>@/g);
    var value_arr_length = value_arr.length-1;
    var value_textArea = "";
    var highlighted_value = "";
    var hiddenVal = "";
    var hiddendText = "";
    var hiddentxt = $(dis).closest(".mentionContainer").find(".mentionHiddenText").val();
    var pattern = /@\[(.*?)\]/g;
    var hidden_array = hiddentxt.match(pattern);
    var forHidden = "";
    var forHiden_arr = "";
    if(value_arr_length==0){
        highlighted_value = prefix+$.trim(activeEle.text());
        value_textArea = prefix+$.trim(activeEle.text());
        highlighted_value = "<span style='' data_id='"+ activeEle.attr("data_id") +"' first_name='"+ activeEle.attr("first_name") +"' last_name='"+ activeEle.attr("last_name") +"'><b class='"+ settings.highlightClass +"'>"+prefix+$.trim(activeEle.text())+"</b></span>";
        $(dis).val(value_textArea);
        $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").eq(0).html(highlighted_value)

        forHidden = "@["+prefix+$.trim(activeEle.attr("last_name")+"_"+activeEle.attr("first_name"))+":"+ activeEle.attr("data_id") +"]";
        $(dis).closest(".mentionContainer").find(".mentionHiddenText").eq(0).val(forHidden)
        // console.log(value)
        // alert(123213)
    }else{
        highlighted_value = prefix+$.trim(activeEle.text());
        var highlighted_value2 = highlighted_value;
        var replace_last_word = "@"+value_arr[value_arr_length];
        replace_last_word = replace_last_word.replace(/\(/g,"\\(").replace(/\)/g,"\\)");
        var re = new RegExp(replace_last_word+"(?![\\s\\S]*"+replace_last_word+")");
        // alert(value_txt)
        // value_txt =  value_txt.replace(re, '');
        forHidden = value_txt.replace(re,'');
        // value_textArea = value_txt+highlighted_value;
        var searchValLength = AlertPrevWord(dis).length+1;
        var insertCaret = dis.selectionStart-searchValLength;
        var gg = value_txt.split("");

        var focusCaret = insertCaret+highlighted_value2.length;
        var countAndActiveEle = 0;
        var caretPos = dis.selectionStart-searchValLength-1;
        // console.log(insertCaret)

        for(var h in gg){
            countAndActiveEle = parseInt(h)+parseInt(activeEle.text().length);
            countAndActiveEleAndSearchVal = parseInt(focusCaret)+parseInt(searchValLength)
            if(countAndActiveEle>=focusCaret && countAndActiveEle<countAndActiveEleAndSearchVal){
                // console.log(focusCaret+" ;; "+countAndActiveEle);
                continue;
            }
            if(gg[h]!=""){
                value_textArea += gg[h];
                if(h==caretPos){
                    value_textArea += highlighted_value;
                }
                // console.log(h +" == "+ caretPos)
                // console.log(value_textArea)
            }
        }
        highlighted_value = "<span style='' data_id='"+ activeEle.attr("data_id") +"' first_name='"+ activeEle.attr("first_name") +"' last_name='"+ activeEle.attr("last_name") +"'><b class='"+ settings.highlightClass +"'>"+highlighted_value+"</b></span>";
    
        var array_push = [];
        $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").find("span").each(function(){
            if(array_push.indexOf($(this).text())==-1){
                reg = new RegExp($(this).text(),"g");
                reg_hidden = new RegExp($(this).text(),"g")
                value_txt = value_txt.replace(reg,"<span style='' data_id='"+ $(this).attr("data_id") +"' last_name='"+ $(this).attr("last_name") +"' first_name='"+ $(this).attr("first_name") +"'><b class='"+ settings.highlightClass +"'>"+$(this).text()+"</b></span>");
                forHidden = forHidden.replace(reg,"@["+$(this).attr("first_name")+"_"+$(this).attr("last_name")+":"+ $(this).attr("data_id") +"]");
            }
            array_push.push($(this).text())
        })
        $(dis).closest(".mentionContainer").find(".mentionSelectedContainer").eq(0).html(value_txt+highlighted_value)
        forHidden = forHidden+"@["+prefix+$.trim(activeEle.attr("last_name")+"_"+activeEle.attr("first_name"))+":"+ activeEle.attr("data_id") +"]";
        $(dis).closest(".mentionContainer").find(".mentionHiddenText").eq(0).val(forHidden)
        $(dis).val(value_textArea);
        var focusCaret = insertCaret+highlighted_value2.length+1;
        $(dis).selectRange(focusCaret,focusCaret);
    }
    countIndexSearch = 0;
}
$(document).ready(function  (argument) {

    var json_a = [
        {
            "id": 1,
            "name": "Textbox 1"
        },{
            "id": 1,
            "name": "Textbox 2"
        },{
            "id": 1,
            "name": "Textbox 3"
        },{
            "id": 1,
            "name": "Textbox 4"
        },{
            "id": 1,
            "name": "Combobox 1"
        }
    ];
    // $(".mention_2_text").on({
    //     "keydown" : function(e){
            
    //     },
    //     "keyup" : function(){
    //         var value = $(this).val();
    //         console.log(value)
    //         $(this).closest(".mention_2_container").find(".mention_2_div").html(value);
    //         $(this).val("")
    //     }
    // })

    // $.getJSON("/js/functions/data.json",function(data){
    //     $("#mention-name").mention({
    //     json : data

    //     });
    // });
    
    $.post("/ajax/request_viewer",{action:"getUsers"},function(data){
        // console.log(data)
        data = JSON.parse(data);

        $(".getPost").mention_post({
            json : data

        });
        
        $(".getPost").hashtags("hashTagPost");
        $(".highlighter").css("width","680px")
    })
    limitText(".mentionList_txt",37);


    $(".panda").click(function(){
        var array_push = [];
        var forHidden = $("#mention-post").val();
        $(".mentionSelectedContainer").find("span").each(function(){
            if(array_push.indexOf($(this).text())==-1){
                reg = new RegExp($(this).text(),"g");
                reg_hidden = new RegExp($(this).text(),"g")
                forHidden = forHidden.replace(reg,"@"+$(this).text()+"");
            }
            array_push.push($(this).text())
        })
        console.log(forHidden)
    })
})
function nl3br(varTest){
    return varTest.replace(/&lt;br&gt;/g,'<br>').replace(/&#039;/g,"'");
}
function if_null(str){
    if(str=="" || str==null || str=="null"){
        return "";
    }else{
        return str;
    }
}
function ReturnWord(text, caretPos) {
    var index = text.indexOf(caretPos);
    var preText = text.substring(0, caretPos);
    var words = preText.split("@");
    if(words.length>=2){
        return words[words.length-1];
    }
    
}

function AlertPrevWord(dis) {
    var text = $(dis).val()
    var caretPos = GetCaretPosition(dis)
    var word = ReturnWord(text, caretPos);
    if (word != null) {
        return word;
    }

}

function GetCaretPosition(ctrl) {
    var CaretPos = 0;   // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;
    return (CaretPos);
}
$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};